/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.dd.DDType;
import com.je.common.base.entity.QueryInfo;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.ArrayUtils;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.rpc.excel.ExcelAssistRpcService;
import com.je.meta.service.ExcelAssistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
public class ExcelAssistServiceImpl implements ExcelAssistService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private ExcelAssistRpcService excelAssistRpcService;
    @Autowired
    private MetaResourceService metaResourceService;
    @Autowired
    private CommonService commonService;

    @Override
    public void parseAllDzValues(DynaBean field, Map<String, Object> paramValues, Map<String, List<DynaBean>> dzValues, List<String> dzFields, Map<String, String> requestParams) {
        //选择其他表数据
        //字典设定
        String[] ddXtypes = new String[]{"cbbfield", "treessfield", "treessareafield", "cgroup", "rgroup"};
        String[] tableXtypes = new String[]{"gridssfield", "gridssareafield", "searchfield"};
        if ("1".equals(field.getStr("EXCELFIELD_CLDZ")) && StringUtil.isNotEmpty(field.getStr("EXCELFIELD_DBZDPZ"))) {
            //拉取结果集  根据字段类型拉取所有数据集  字段也要返回dynaBean  text code id
            String dzclType = field.getStr("EXCELFIELD_SJCL");
            if (!"ONE".equals(dzclType)) {
                String xtype = field.getStr("EXCELFIELD_XTYPE");
                if (ArrayUtils.contains(tableXtypes, xtype)) {
                    String dzTableCode = field.getStr("EXCELFIELD_TABLECODE");
                    String dzQuerySql = field.getStr("EXCELFIELD_QUERYSQL");
                    if (StringUtil.isNotEmpty(dzQuerySql)) {
                        dzQuerySql = StringUtil.parseKeyWord(dzQuerySql, paramValues);
                    }
                    List<DynaBean> dzLists = metaService.select(dzTableCode, ConditionsWrapper.builder().apply(dzQuerySql));
                    dzValues.put(field.getStr("EXCELFIELD_CODE"), dzLists);
                    //获取字典项
                } else if (ArrayUtils.contains(ddXtypes, xtype)) {
                    String configInfo = field.getStr("EXCELFIELD_CONFIGINFO");
                    List<DynaBean> lists = new ArrayList<DynaBean>();
                    if (StringUtil.isNotEmpty(configInfo)) {
                        String ddCode = configInfo.split(ArrayUtils.SPLIT)[0];
                        List<JSONTreeNode> dzLists = excelAssistRpcService.getAllTyepDdListItems(ddCode, requestParams, new QueryInfo(), false);
                        for (JSONTreeNode dzItem : dzLists) {
                            DynaBean bean = new DynaBean();
                            bean.set("text", dzItem.getText());
                            bean.set("code", dzItem.getCode());
                            bean.set("id", dzItem.getId());
                            bean.set("bean", dzItem.getBean());
                            lists.add(bean);
                        }
                    }
                    dzValues.put(field.getStr("EXCELFIELD_CODE"), lists);
                }
            }
            if (dzFields != null) {
                dzFields.add(field.getStr("EXCELFIELD_CODE"));
            }
        }
    }

    @Override
    public void doSetBeanDzValue(DynaBean fieldInfo, DynaBean dynaBean, Map<String, List<DynaBean>> dzValues, Map<String, Object> paramValues) {
        String dzclType = fieldInfo.getStr("EXCELFIELD_SJCL");
        String fieldCode = fieldInfo.getStr("EXCELFIELD_CODE");
        String configInfo = fieldInfo.getStr("EXCELFIELD_CONFIGINFO");
        String dbConfigInfo = fieldInfo.getStr("EXCELFIELD_DBZDPZ");
        String[] thisFields = configInfo.split(ArrayUtils.SPLIT)[1].split("~");
        String[] targFields = configInfo.split(ArrayUtils.SPLIT)[2].split("~");
        String value = dynaBean.getStr(fieldCode);
        String xtype = fieldInfo.getStr("EXCELFIELD_XTYPE");
        String[] ddXtypes = new String[]{"cbbfield", "treessfield", "treessareafield", "cgroup", "rgroup"};
        String[] tableXtypes = new String[]{"gridssfield", "gridssareafield", "searchfield", "queryuserfield", "queryuserareafield"};
        if (StringUtil.isNotEmpty(value) && StringUtil.isNotEmpty(configInfo) && StringUtil.isNotEmpty(dbConfigInfo)) {
            if (!"ONE".equals(dzclType)) {
                List<DynaBean> lists = dzValues.get(fieldCode);
                for (DynaBean data : lists) {
                    // EDIT BY ZHANGYD 20201111 FOR 查询选择无法正常带值
                    Boolean flag = false;
                    for (String dbInfo : dbConfigInfo.split(",")) {
                        if (!flag) {
                            String thisField = dbInfo.split("~")[0];
                            String targField = dbInfo.split("~")[1];
                            if (StringUtil.isNotEmpty(dynaBean.getStr(thisField)) && data.getStr(targField, "").equals(dynaBean.getStr(thisField))) {
                                flag = true;
                            }
                        }
                    }
                    // EDIT BY ZHANGYD 20201111 FOR 查询选择无法正常带值 end
                    //找到了数据
                    if (flag) {
                        for (int i = 0; i < targFields.length; i++) {
                            String targerField = targFields[i];
                            if (thisFields.length > i) {
                                String thisField = thisFields[i];
                                dynaBean.set(thisField, data.get(targerField));
                            }
                        }
                    }
                }
            } else {
                if (ArrayUtils.contains(tableXtypes, xtype)) {
                    String dzTableCode = fieldInfo.getStr("EXCELFIELD_TABLECODE");
                    String dzQuerySql = fieldInfo.getStr("EXCELFIELD_QUERYSQL");
                    Map<String, Object> beanSet = dynaBean.clone().getValues();
                    if (StringUtil.isNotEmpty(dzQuerySql)) {
                        dzQuerySql = StringUtil.parseKeyWord(dzQuerySql, paramValues);
                        dzQuerySql = StringUtil.parseKeyWord(dzQuerySql, beanSet);
                    }
                    List<String> sqlWheres = new ArrayList();
                    for (String dbInfo : dbConfigInfo.split(",")) {
                        String thisField = dbInfo.split("~")[0];
                        String targField = dbInfo.split("~")[1];
                        sqlWheres.add(" " + targField + "='" + dynaBean.getStr(thisField) + "'");
                    }
                    List<DynaBean> dzLists = metaService.select(dzTableCode, ConditionsWrapper.builder().apply(dzQuerySql + " AND (" + StringUtil.buildSplitString(ArrayUtils.getArray(sqlWheres), " AND ") + ")"));
                    if (dzLists.size() > 0) {
                        DynaBean data = dzLists.get(0);
                        for (int i = 0; i < targFields.length; i++) {
                            String targerField = targFields[i];
                            if (thisFields.length > i) {
                                String thisField = thisFields[i];
                                dynaBean.set(thisField, data.get(targerField));
                            }
                        }
                    }
                } else if (ArrayUtils.contains(ddXtypes, xtype)) {
                    String ddCode = configInfo.split(ArrayUtils.SPLIT)[0];
                    DynaBean dictionary = metaService.selectOne("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("DICTIONARY_DDCODE", ddCode)
                            .apply("and (SY_STATUS = '' or SY_STATUS = '1')"));
                    if (dictionary != null) {
                        String ddType = dictionary.getStr("DICTIONARY_DDTYPE");
                        Map<String, String> ddFields = new HashMap();
                        ddFields.put("text", "DICTIONARYITEM_ITEMNAME");
                        ddFields.put("code", "DICTIONARYITEM_ITEMCODE");
                        ddFields.put("id", "JE_CORE_DICTIONARYITEM_ID");
                        List<String> sqlWheres = new ArrayList<String>();
                        for (String dbInfo : dbConfigInfo.split(",")) {
                            String thisField = dbInfo.split("~")[0];
                            String targField = dbInfo.split("~")[1];
                            sqlWheres.add(" " + ddFields.get(targField) + "='" + dynaBean.getStr(thisField) + "'");
                        }
                        if (DDType.LIST.equalsIgnoreCase(ddType) || DDType.TREE.equalsIgnoreCase(ddType)) {
                            List<DynaBean> dzLists = metaService.select("JE_CORE_DICTIONARYITEM", ConditionsWrapper.builder().apply(" AND DICTIONARYITEM_DICTIONARY_ID='" + dictionary.getStr("JE_CORE_DICTIONARY_ID") + "' AND (" + StringUtil.buildSplitString(ArrayUtils.getArray(sqlWheres), " AND ") + ")"));
                            if (dzLists.size() > 0) {
                                DynaBean data = dzLists.get(0);
                                for (int i = 0; i < targFields.length; i++) {
                                    String targerField = targFields[i];
                                    if (thisFields.length > i) {
                                        String thisField = thisFields[i];
                                        dynaBean.set(thisField, data.get(ddFields.get(targerField)));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void temporarySaveData(DynaBean group, DynaBean sheet, List<DynaBean> datas, List<DynaBean> fields, String groupTemId) {
        if (datas != null && datas.size() > 0) {
            String SHEETNAME = sheet.getStr("sheetName");
            int sheetOrder = sheet.getInt("SY_ORDERINDEX", 1) - 1;
            if (StringUtil.isEmpty(groupTemId)) {
                List<DynaBean> list = metaResourceService.selectByTableCodeAndNativeQuery("JE_EXCEL_GROUPTEM", NativeQuery.build().eq("JE_CORE_EXCELGROUP_ID", group.getStr("JE_CORE_EXCELGROUP_ID")));
                DynaBean groupTem = new DynaBean("JE_EXCEL_GROUPTEM", true);
                if (list.isEmpty()) {
                    groupTem.set("GROUPNAME", group.getStr("GROUPNAME"));
                    groupTem.set("GROUPCODE", group.getStr("GROUPCODE"));
                    groupTem.set("JE_CORE_EXCELGROUP_ID", group.getStr("JE_CORE_EXCELGROUP_ID"));
                    commonService.buildModelCreateInfo(groupTem);
                    groupTem = metaResourceService.insert(groupTem);
                } else {
                    groupTem = list.get(0);
                }
                groupTemId = groupTem.getStr("JE_EXCEL_GROUPTEM_ID");
            }
            List<DynaBean> list = metaResourceService.selectByTableCodeAndNativeQuery("JE_EXCEL_CONFIGTEMP", NativeQuery.build().eq("JE_CORE_EXCELSHEET_ID", sheet.getStr("JE_CORE_EXCELSHEET_ID")));
            //声明字段对应
            List<String> fieldConfigs = new ArrayList<String>();
            DynaBean previewConfig = new DynaBean("JE_EXCEL_CONFIGTEMP", true);
            if (list.isEmpty()) {
                previewConfig.set("GROUPNAME", group.getStr("GROUPNAME"));
                previewConfig.set("GROUPCODE", group.getStr("GROUPCODE"));
                previewConfig.set("SHEETNAME", SHEETNAME);
                previewConfig.set("JE_EXCEL_GROUPTEM_ID", groupTemId);
                previewConfig.set("JE_CORE_EXCELGROUP_ID", group.getStr("JE_CORE_EXCELGROUP_ID"));
                previewConfig.set("CONFIGTEMP_SHEET", sheetOrder);
                previewConfig.set("JE_CORE_EXCELSHEET_ID", sheet.getStr("JE_CORE_EXCELSHEET_ID"));
                previewConfig.set("CONFIGTEMP_SHEETNAME", SHEETNAME);
                commonService.buildModelCreateInfo(previewConfig);
                for (int i = 0; i < fields.size(); i++) {
                    DynaBean field = fields.get(i);
                    fieldConfigs.add("DATATEMP_FIELD" + (i + 1) + "~" + field.getStr("EXCELFIELD_CODE"));
                }
                previewConfig.set("CONFIGTEMP_FIELDCONFIG", StringUtil.buildSplitString(ArrayUtils.getArray(fieldConfigs), ","));
                previewConfig = metaResourceService.insertByTableCode("JE_EXCEL_CONFIGTEMP", previewConfig);
            } else {
                previewConfig = list.get(0);
                fieldConfigs = Arrays.asList(previewConfig.getStr("CONFIGTEMP_FIELDCONFIG").split(","));
            }
            int index = 1;
            for (DynaBean data : datas) {
                DynaBean temData = new DynaBean("JE_EXCEL_DATATEMP", true);
                for (String fieldConfig : fieldConfigs) {
                    String fieldCode = fieldConfig.split("~")[0];
                    String fieldTarge = fieldConfig.split("~")[1];
                    temData.set(fieldCode, data.getStr(fieldTarge));
                }
                temData.set("CODE", data.getStr("__CODE__"));
                temData.set("MSG", data.getStr("__MSG__"));
                temData.set("JE_EXCEL_CONFIGTEMP_ID", previewConfig.getStr("JE_EXCEL_CONFIGTEMP_ID"));
                //temData.set("SY_ORDERINDEX", index);
                commonService.buildModelCreateInfo(temData);
                metaResourceService.insert(temData);
                index++;
            }
        }
    }

    @Override
    public JSONObject buildSheetInfo(DynaBean group, DynaBean sheet) {
        DynaBean previewConfig = metaResourceService.selectOneByNativeQuery("JE_EXCEL_CONFIGTEMP", NativeQuery.build().eq("JE_CORE_EXCELSHEET_ID", sheet.getStr("JE_CORE_EXCELSHEET_ID")));
        JSONObject returnObj = new JSONObject();
        if (previewConfig != null) {
            int sheetOrder = sheet.getInt("SY_ORDERINDEX", 1) - 1;
            returnObj.put("sheetName", sheet.getStr("sheetName"));
            returnObj.put("sheetIndex", sheetOrder);
            returnObj.put("temId", previewConfig.getStr("JE_EXCEL_CONFIGTEMP_ID"));
            List<DynaBean> fields = metaResourceService.selectByTableCodeAndNativeQuery("JE_CORE_EXCELFIELD",
                    NativeQuery.build().eq("JE_CORE_EXCELSHEET_ID", sheet.getStr("JE_CORE_EXCELSHEET_ID")).orderByAsc("SY_ORDERINDEX"));

            JSONArray columns = new JSONArray();
            for (int i = 0; i < fields.size(); i++) {
                DynaBean fieldInfo = fields.get(i);
                String targerCode = "DATATEMP_FIELD" + (i + 1);
                JSONObject column = new JSONObject();
                JSONObject field = new JSONObject();
                if ("rownumberer".equals(fieldInfo.getStr("EXCELFIELD_XTYPE"))) {
                    continue;
                }
                column.put("dataIndex", targerCode);
                column.put("hidden", "1".equals(fieldInfo.get("EXCELFIELD_HIDDEN")));
                column.put("text", fieldInfo.getStr("EXCELFIELD_NAME"));
                column.put("width", fieldInfo.getInt("EXCELFIELD_WIDTH", 80));
                field.put("name", targerCode);
                field.put("xtype", fieldInfo.getStr("EXCELFIELD_XTYPE"));
                String configInfo = fieldInfo.getStr("EXCELFIELD_CONFIGINFO", "");
                if (StringUtil.isNotEmpty(configInfo)) {
                    if (ArrayUtils.contains(new String[]{"rgroup", "cgroup", "cbbfield", "treessfield", "treessareafield", "gridssfield", "gridssareafield", "searchfield", "queryuserfield", "queryuserareafield"}, fieldInfo.getStr("EXCELFIELD_XTYPE"))) {
                        String[] confArray = configInfo.split(ArrayUtils.SPLIT);
                        if (confArray.length > 1) {
                            String thisFields = confArray[1];
                            String[] thisFieldArray = thisFields.split("~");
                            for (int j = 0; j < thisFieldArray.length; j++) {
                                thisFieldArray[j] = StringUtil.getDefaultValue(targerCode, thisFieldArray[j]);
                            }
                            confArray[1] = StringUtil.buildSplitString(thisFieldArray, "~");
                            configInfo = StringUtil.buildSplitString(confArray, ",");
                        }
                    }
                }
                field.put("configInfo", configInfo);
                field.put("value", fieldInfo.getStr("EXCELFIELD_VALUE"));
                column.put("field", field);
                columns.add(column);
            }
            returnObj.put("columns", columns);
        }

        return returnObj;
    }
}
